package com.pek.control.controller;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pek.util.RestResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/domain")
public class DomainController {
    @Value("${yeyv.domain}")
    public String domainName;

    @GetMapping("/validateLogin")
    public boolean validateLogin() {
        return true;
    }

    @PostMapping("/uploadFile")
    @ResponseBody
    public RestResult<String[]> uploadFile(
            @RequestParam(defaultValue = "false") boolean overwrite,
            @RequestParam(defaultValue = "/product") String prefix,
            @RequestBody MultipartFile[] files) throws IOException {
        String[] result = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            var file = files[i];
            var dir = new File(
                    "./files/" +
                            (prefix.charAt(0) == '/' ?
                                    prefix.substring(1) :
                                    prefix)
            );
            if (!dir.exists()) {
                dir.mkdirs();
            }
            System.out.println(file.getSize());
            if (file.getSize() >= 51200000) {
                return RestResult.error("请选择小于50MB的文件进行上传！");
            }
            var formFile = new File(dir.getPath() + "/" + file.getOriginalFilename());
            //如果文件已存在并且不重写文件
            if (formFile.exists() && !overwrite) {
                result[i] = domainName + formFile.getPath().replace("\\", "/").substring(domainName.endsWith("/") ? 2 : 1);
                continue;
            }
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(formFile)
            );
            stream.write(bytes);
            stream.close();
            result[i] = domainName + formFile.getPath().replace("\\", "/").substring(domainName.endsWith("/") ? 2 : 1);
            log.info("Create File : " + result[i]);
        }
        return RestResult.success(result);
    }
}
